<?php
/*
 * Author: Quan Van Sinh
 * Email : sinhvnb@vietnambiz.com
 * Mobile: 0972405165
*/
//category function
function addNewCategory() {
    global $db,$CONFIG;
    if(isset($_POST['submitFrmNewsAddCategory'])) {
        $data = array();
        if($_POST['cat_title']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
        }
        $data['cat_title'] = $_POST['cat_title'];
        $data['cat_parent'] = $_POST['cat_parent'];
        $data['cat_link'] = create_link($_POST['cat_title']);
        $data['cat_link'] = checkCatLinkExist($data['cat_link']);
        $data['cat_description'] = $_POST['cat_description'];
        $data['create_date'] = date('Y-m-d H:i:s');
        $data['cat_active'] = $_POST['cat_active'];
        $data['user_id'] = $_SESSION['adlogin']["id"];

        if($CONFIG["error_message"]=='') {
            unset ($_REQUEST);
            $bigestOrder = getBigestOrder();
            $data['cat_order'] = $bigestOrder+1;
            $db->exec_insert('cat_document', $data);
            $CONFIG["success_message"] = "<li>Thêm mới danh mục thành công!</li>";
            if($_POST['submitType']=='exit') {
                server_redirect(SITE_URL . get_string_url(array('action')));
            }
        }
    }
}

function editUpdateCategory() {
    global $db,$CONFIG;
    $cat_id = intval($_REQUEST['cat_id']);
    if($cat_id>0) {
        if(isset($_POST['submitFrmNewsAddCategory'])) {//update category
            $data = array();
            if($_POST['cat_title']=='') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
            }
            $data['cat_title'] = $_POST['cat_title'];
            $data['cat_parent'] = $_POST['cat_parent'];
            $data['cat_link'] = create_link($_POST['cat_title']);
            $data['cat_description'] = filter($_POST['cat_description']);
            $data['create_date'] = date('Y-m-d H:i:s');
            $data['cat_active'] = filter($_POST['cat_active']);
            $data['user_id'] = $_SESSION['adlogin']["id"];
            if($CONFIG["error_message"]=='') {
                $db->exec_update('cat_document', $data, " cat_id=$cat_id ");
                $CONFIG["success_message"] = "<li>Cập nhật danh mục thành công!</li>";
                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL . get_string_url(array('action')));
                }
            }
        }
        return $db->query_first("SELECT * FROM cat_document WHERE cat_id=$cat_id");
    }
}

function deleteNewsCat() {
    global $db;
    $cat_id = intval($_REQUEST['cat_id']);
    if($cat_id>0) {
        $arrChildCatNews = getCatNewsIdToArray($cat_id,$trees=null);
        for($i=0;$i<count($arrChildCatNews);$i++) {
            if(intval($arrChildCatNews[$i])>0) {
                $db->exec_delete('cat_document',"cat_id=".$arrChildCatNews[$i]);
            }
        }
        $db->exec_delete('cat_document',"cat_id=$cat_id");
    }
}

function getCatNewsIdToArray($parent_id = 0,$trees=null) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT cat_id FROM cat_document WHERE  cat_parent = ".intval($parent_id));
    if($rsCat) {
        while($rs = $db->fetch_array($rsCat)) {
            $trees[] = $rs['cat_id'];
            $trees = getCatNewsIdToArray($rs['cat_id'],$trees);
        }
    }
    return $trees;
}

function listAllNewsCategory($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM cat_document WHERE  cat_parent = ".intval($parent_id)." ORDER BY cat_order");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['cat_parent']==0) {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$space.$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }
        $trees = listAllNewsCategory($rs['cat_id'],$space.'----',$trees);
    }
    return $trees;
}

function multiActionCategoryNews() {
    global $db;
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
        $arrCatId = $_REQUEST['arr_cat_id'];
        switch($_REQUEST['formNewsCategoryViewAction']) {
            case "delete": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_delete('cat_news','cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
            }case


            "setStatusYes": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_update('cat_news',array("cat_active"=>'yes'),'cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
            }case


            "setStatusNo": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_update('cat_news',array("cat_active"=>'no'),'cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
                }
        }
    }
}

//order category
function orderNewsCategory() {
    global $db,$CONFIG,$option;
    if(isset($_POST['submitFrmNewsOrder']) && $_POST['submitFrmNewsOrder']=="Submit") {//update
        $arrNewsCatID = $_POST['news_order'];
        if(count($arrNewsCatID)) {
            for($i=0;$i<count($arrNewsCatID);$i++) {
                if(intval($arrNewsCatID[$i])>0) {
                    $db->exec_update('cat_news',array("cat_order"=>$i),'cat_id='.intval($arrNewsCatID[$i]));
                }
            }
            if($_POST['submitType']=='exit') {
                server_redirect(SITE_URL.get_string_url(array('action')));
            }else {
                return listAllNewsCategory();
            }
        }else {
            return listAllNewsCategory();
        }
    }else {//show
        return listAllNewsCategory();
    }

}

// Le Trong Phuc
//end category function
//news
//Uporder category function
function upOrderNewsCategory() {
    global $db;
    $cat_id = $_REQUEST['cat_id'];

    $arr_cat_order = getOrder($cat_id);
    $cat_order = $arr_cat_order['cat_order'];
    $cat_parent = $arr_cat_order['cat_parent'];

    $arrCatUp = getUpOrder($cat_order,$cat_parent);
    $catUpId = $arrCatUp['cat_id'];
    $catUpOrder = $arrCatUp['cat_order'];
    $data = array();
    $data['cat_order'] = $cat_order;
    $dataUp = array();
    $dataUp['cat_order'] = $catUpOrder;
    //$db->exec_update('cat_news', $dataUp, " cat_id=$catUpId");
    if(intval($catUpId>0)) {
        $db->query("update cat_document set cat_order=$catUpOrder where cat_id=$cat_id");
        $db->query("update cat_document set cat_order=$cat_order where cat_id=$catUpId");
    }
}
function getOrder($cat_id) {
    global $db;
    $rsCat = $db->query_first("SELECT cat_order,cat_parent FROM cat_document WHERE  cat_id = ".intval($cat_id));
    return $rsCat;
}
function getUpOrder($cat_order,$cat_parent) {
    global $db;
    $rsCat = $db->query_first("SELECT cat_id,cat_order FROM cat_document WHERE  cat_order<$cat_order AND cat_parent=$cat_parent ORDER BY cat_order DESC");
    return array("cat_id"=>$rsCat['cat_id'],"cat_order"=>$rsCat['cat_order']);
}
function downOrderNewsCategory() {
    global $db;
    $cat_id = $_REQUEST['cat_id'];

    $arr_cat_order = getOrder($cat_id);
    $cat_order = $arr_cat_order['cat_order'];
    $cat_parent = $arr_cat_order['cat_parent'];
    $arrCatDown = getDownOrder($cat_order,$cat_parent);
    $catDownId = $arrCatDown['cat_id'];
    $catDownOrder = $arrCatDown['cat_order'];
    $data = array();
    $data['cat_order'] = $cat_order;


    $dataUp = array();
    $dataUp['cat_order'] = $catDownOrder;
    //$db->exec_update('cat_news', $dataUp, " cat_id=$catUpId");
    if(intval($catDownId)>0) {
        $db->query("update cat_document set cat_order=$catDownOrder where cat_id=$cat_id");
        $db->query("update cat_document set cat_order=$cat_order where cat_id=$catDownId");
    }


}
function getDownOrder($cat_order,$cat_parent) {
    global $db;
    $rsCat = $db->query_first("SELECT cat_id,cat_order FROM cat_document WHERE  cat_order>$cat_order AND cat_parent=$cat_parent ORDER BY cat_order ASC");
    return array("cat_id"=>$rsCat['cat_id'],"cat_order"=>$rsCat['cat_order']);
}

function getBigestOrder() {
    global $db;
    $rsCat = $db->query_first("SELECT cat_order FROM cat_document ORDER BY cat_order DESC");
    return $rsCat['cat_order'];
}
// End Le Trong Phuc
//end category function
//news
function addNewNews() {
    global $db,$CONFIG;
    $upload_dir = $CONFIG ['upload_dir'].'/images/partner/'.date("Y").'/'.date("m");
    $upload_url = '/uploads/images/partner/'.date("Y").'/'.date("m");

    if(isset($_POST['submitFrmNewsAdd'])) {
        $data = array();

        $docs = $_FILES['file'];
        if($_POST['title']=='' || $_POST['title']==' ') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
        }
        if($_POST['link']=='' || $_POST['link']=='http://') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập liên kết!</li>";
        }
      
        if($docs['name']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa chọn file để tải lên!</li>";
        }
        $data['title'] = $_POST['title'];
        $data['link'] = $_POST['link'];
        $data['description'] = $_POST['description'];
        $data['status'] = $_POST['status'];
        $data['create_date'] = date('Y-m-d H:i:s');



        if($CONFIG["error_message"]=='') {

            $time = rand(0000000000,9999999999) .'-'. time();
            $realName = $docs['name'];
            $arrDocNameExplode = explode('.', $docs["name"]);
            $docExtention = $arrDocNameExplode[(count($arrDocNameExplode)-1)];
            $filename = $time.'.'.strtolower($docExtention);
            $data['filename'] = $upload_url."/".$filename;
            $data['realname'] = $realName;
            if (!file_exists($upload_dir)) {
                if(!mkdir($upload_dir, 0777,true)) {
                    $CONFIG["error_message"] .= "<li>Không thể tạo thư mục, kiểm tra lại quyền của bạn.</li>";
                }
            }
            if (move_uploaded_file($docs["tmp_name"],$upload_dir."/".$filename)) {
                $db->exec_insert('partner', $data);
            }

            if($_POST['submitType']=='exit') {
                //server_redirect(ADMIN_URL . '?module=news');
                server_redirect(SITE_URL . get_string_url(array('action')));
            }
            $CONFIG["success_message"] = "<li>Thêm mới đối tác thành công!</li>";
        }

    }
}

function checkNewsLinkExist($newsLink) {
    global $db;
    $rs = $db->query_first("SELECT id,title_link FROM projects WHERE title_link='$newsLink'");
    if(intval($rs['id'])>0) {
        $newsLink = $rs['title_link'].'-'.rand(0,9);
        checkNewsLinkExist($newsLink);
    }
    return $newsLink;
}

function checkCatLinkExist($newsCatLink) {
    global $db;
    $rs = $db->query_first("SELECT cat_id,cat_link FROM cat_document WHERE cat_link='$newsCatLink'");
    if(intval($rs['cat_id'])>0) {
        $newsCatLink = $rs['cat_link'].'-'.rand(0,9);
        checkCatLinkExist($newsCatLink);
    }
    return $newsCatLink;
}

function checkTagExist($tag) {
    global $db;
    $rs = $db->query_first("SELECT id FROM tags_news WHERE tags='$tag'");
    if($rs) {
        return $rs['id'];
    }else {
        return 'donthave';
    }
}

function editUpdateNews() {
    global $db,$CONFIG;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        if(isset($_POST['submitFrmNewsAdd'])) {//update category
            $data = array();

            if($_POST['title']=='' || $_POST['title']==' ') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
            }
            if($_POST['link']=='' || $_POST['link']=='http://') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập liên kết!</li>";
            }
           

            
            $data['title'] = $_POST['title'];
            $data['link'] = $_POST['link'];
            $data['description'] = $_POST['description'];
            $data['status'] = $_POST['status'];

            if($CONFIG["error_message"]=='') {
                $db->exec_update('partner', $data, " id=$id ");
                $CONFIG["success_message"] = "<li>Cập nhật đối tác thành công!</li>";

                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL . get_string_url(array('action','id')));
                }
            }
        }

        $rsNewsEdit = $db->query_first("SELECT * FROM partner WHERE id=$id");
        return array("rsNewsEdit"=>$rsNewsEdit);
    }else {
        server_redirect(SITE_URL . get_string_url(array('action','id')));
    }

}

function newsDetail() {
    global $db;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        return $db->query_first("SELECT * FROM projects WHERE id=$id");
    }else {
        server_redirect(ADMIN_URL.'?module=projects');
    }
}

function deleteNews() {
    global $db;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        $sql = "SELECT filename FROM partner WHERE id=$id";
        $rs = $db->query_first($sql);
        @unlink(SITE_BASE_DIR.$rs['filename']);
        $db->exec_delete('partner',"id=$id");

    }
}

function listAllNews() {
    global $db,$CONFIG;
    if(intval($_REQUEST['page'])>0) {
        $page = $_REQUEST['page'];
    }else {
        $page = 1;
    }
    // neu' bam vao nut tim kiem
    if($_REQUEST['submitFrmNewsSearch']=='Search') {
        if($_REQUEST['keyword']!='') {
            $searchCondition = ' AND (n.realname LIKE \'%'.$_REQUEST['keyword'].'%\') ';
        }
        
        //echo $searchCondition;
        $rsNews = $db->query("SELECT n.id FROM partner n WHERE 1 $searchCondition ORDER BY n.create_date DESC");
        $totalRows =  $db->num_rows($rsNews);
        $totalPages = ceil($totalRows/$CONFIG ['rows_per_page_news']);
        $start = (($page*$CONFIG ['rows_per_page_news'])-$CONFIG ['rows_per_page_news']);
        $limit = $CONFIG ['rows_per_page_news'];

        $rs = $db->query("SELECT n.*
                            FROM partner n
                            WHERE 1 $searchCondition ORDER BY n.create_date DESC LIMIT $start,$limit");
        //chuyen ve` truong truoc neu' trang hien tai khong co' ban ghi nao (truong hop xoa)
        if($db->num_rows($rs)<1) {
            $page = $page - 1;
            if($page>1) {
                server_redirect(get_string_url()."&page=".$page);
            }

        }
        return array(
                "rs"=>$rs,
                "page"=>$page,
                "totalPages"=>$totalPages
        );
    }else {
        $rsNews = $db->query("SELECT n.id FROM partner n WHERE 1 ORDER BY n.create_date DESC");
        $totalRows =  $db->num_rows($rsNews);
        $totalPages = ceil($totalRows/$CONFIG ['rows_per_page_news']);
        $start = (($page*$CONFIG ['rows_per_page_news'])-$CONFIG ['rows_per_page_news']);
        $limit = $CONFIG ['rows_per_page_news'];

        $rs = $db->query("SELECT n.*
                            FROM partner n
                            WHERE 1 ORDER BY n.create_date DESC LIMIT $start,$limit");
        //chuyen ve` truong truoc neu' trang hien tai khong co' ban ghi nao (truong hop xoa)
        if($db->num_rows($rs)<1) {
            $page = $page - 1;
            if($page>1) {
                redirect(get_string_url()."&page=".$page);
            }

        }
        return array(
                "rs"=>$rs,
                "page"=>$page,
                "totalPages"=>$totalPages
        );
    }
}

function multiActionNews() {
    global $db;
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
        $arrNewsId = $_REQUEST['arr_news_id'];
        switch($_REQUEST['formNewsViewAction']) {
            case "delete": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $sql = "SELECT filename FROM partner WHERE id=".intval($arrNewsId[$i]);
                            $rs = $db->query_first($sql);
                            @unlink(SITE_BASE_DIR.$rs['filename']);
                            $db->exec_delete('partner','id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
            }case


            "setStatusYes": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_update('news',array("active"=>'yes'),'id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
            }case


            "setStatusPending": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_update('news',array("active"=>'pending'),'id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
            }case


            "setStatusNo": {
                    for($i=0;$i<count($arrNewsId);$i++) {
                        if(intval($arrNewsId[$i])>0) {
                            $db->exec_update('news',array("active"=>'no'),'id='.intval($arrNewsId[$i]));
                        }
                    }
                    break;
                }
        }
    }
}
?>
